<!-- 经销商订单弹窗 -->
<template>
  <Dialog
    v-model="dialogVisible"
    :maxHeight="'800px'"
    width="60%"
    title="选择付款单"
    :before-close="() => closeDialog()"
  >
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('orderPayment.orderCode')">
        <el-input
          v-model="form.order_no"
          :disabled="state.is_order_no_disabled"
          clearable
          :placeholder="t('orderPayment.orderCode')"
          style="width: 250px"
        />
      </el-form-item>
      <!-- <el-form-item :label="t('orderPayment.theTypeOfOrder')">
        <el-select
          v-model="form.order_type"
          :placeholder="t('orderPayment.theTypeOfOrder')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in orderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item :label="t('orderPayment.transactionTicketNumber')">
        <el-input
          v-model="form.voucher_code"
          clearable
          :placeholder="t('orderPayment.transactionTicketNumber')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">查询</el-button>
        <el-button icon="Refresh" @click="reset(true)">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格主体 -->
    <el-table
      class="m-t-10px"
      :data="dataList"
      highlight-current-row
      stripe
      border
      ref="tableRef"
      v-loading="tableLoading"
      row-key="id"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        :reserve-selection="true"
        width="55"
        :selectable="(row) => Number(row.paid_amount) !== 0"
      />
      <el-table-column
        :label="t('orderPayment.orderCode')"
        prop="order_no"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        :label="t('orderPayment.theTypeOfOrder')"
        prop="order_type"
        min-width="200"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        :label="t('orderPayment.transactionTicketNumber')"
        prop="voucher_code"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('orderPayment.user')"
        prop="user_name"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('orderPayment.theAmountOfThePayment')"
        prop="paid_amount"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('orderPayment.paymentTime')"
        prop="create_time"
        min-width="200"
        :show-overflow-tooltip="true"
      />
    </el-table>
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog"
        >{{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">{{ t('wholesalOrder.add') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { getPayEnumApi, getListApi } from '@/api/order/pay'
import { Dialog } from '@/components/Dialog'
import { ElMessage } from 'element-plus'

const props = withDefaults(defineProps<{ multiple?: boolean }>(), {
  multiple: false
})
const emit = defineEmits(['exposeMultipleData'])
const { t } = useI18n()
const { query } = useRoute()
const tableRef = ref()

const isReset = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  order_no: '',
  order_type: '',
  voucher_code: '',
  pay_status: '01',
  pay_type: '00',
  invoice_status: '10,30',
  pageIndex: 1,
  pageSize: 15
})

const orderTypeList = ref<Array<Record<string, any>>>([])

const state = reactive({
  is_order_no_disabled: false
})
//批量勾选
const handleSelectionChange = (val: any[]) => {
  if (val.length > 1 && !props.multiple) {
    // 如果选中的行数超过一行， 并且不允许多选，清除之前的选中项，只保留最新的选中项
    const latestSelection = val[val.length - 1]
    tableRef.value.clearSelection()
    tableRef.value.toggleRowSelection(latestSelection, true)
    multipleSelection.value = [latestSelection]
  } else {
    multipleSelection.value = val
  }
}

//点击添加按钮
const submit = () => {
  if (!multipleSelection.value.length) return ElMessage.warning('请勾选付款单')
  if (!props.multiple && multipleSelection.value.length > 1)
    return ElMessage.warning('最多只能勾选一位客户')
  if (props.multiple && isReset.value) {
    const merge = selectionPak.value.concat(multipleSelection.value)
    emit('exposeMultipleData', deduplication(merge))
  } else {
    emit('exposeMultipleData', multipleSelection.value)
  }
  closeDialog()
}

//一维数组去重
const deduplication = (val: any[], key?: string) => {
  if (!val || !val.length) return
  return val.reduce((acc, item) => {
    if (!acc.some((x: Record<string, any>) => x[key ?? 'id'] === item[key ?? 'id'])) {
      acc.push(item)
    }
    return acc
  }, [])
}

//点击取消关闭弹框
const closeDialog = () => {
  reset()
  dialogVisible.value = false
}

//初始化请求
const getList = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  params.role = 'user'
  if (query.id) {
    params.invoive_id = query.id
  }
  console.log(query, params)
  delete params.date
  delete params.order_no
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = (isRequest?: boolean) => {
  form.value = {
    order_no: state.is_order_no_disabled ? form.value.order_no : '',
    order_type: '',
    voucher_code: '',
    invoice_status: '10,30',
    pay_status: '01',
    pay_type: '00',
    pageIndex: 1,
    pageSize: 15
  }
  paginationTotal.value = 0
  multipleSelection.value = []
  nextTick(() => {
    tableRef!.value!.clearSelection()
  })
  if (isRequest) {
    getList()
    isReset.value = true
  }
}

const initialize = (val: any[], orderNo: string, order_ids: string, isOrderNoDisabled: boolean) => {
  // 使用 nextTick 确保 DOM 更新完成后执行
  nextTick(() => {
    form.value.order_no = orderNo
    form.value.order_ids = order_ids
    state.is_order_no_disabled = isOrderNoDisabled
    getDropDownBoxInfo()
    getList()
  })
  if (props.multiple) selectionPak.value = val
  if (!val || !val.length) return
  val.forEach((item: Record<string, any>) => {
    nextTick(() => {
      tableRef!.value!.toggleRowSelection(item, true)
    })
  })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getPayEnumApi({ field: 'all' })
  orderTypeList.value = resp.data.order_type
}

defineExpose({
  dialogVisible,
  initialize
})
</script>

<style lang="less" scoped></style>
